package com.qf.merchant.controller;


import com.qf.common.http.Result;
import com.qf.dto.Goods;
import com.qf.dto.GoodsType;
import com.qf.po.LoginMerchant;
import com.qf.service.impl.GoodsService;
import com.qf.service.impl.GoodsTypeService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.UUID;

@Controller
@RequestMapping("goods")
public class GoodsController {

    @Resource
    private GoodsService goodsService;

    @Resource
    private GoodsTypeService goodsTypeService;

    //通过登入者来显示商品
    @RequestMapping("goods")
    public String toGoods(Model model , LoginMerchant loginMerchant){
       // List<Goods> goods = goodsService.getByMerchantUserId(loginMerchant.getId());
        List<Goods> goods = goodsService.list();
        model.addAttribute("goodsList",goods);

        return "goods/goods";
    }

    @RequestMapping("add")
    public String toAdd(Model model){

        List<GoodsType> goodsTypeList = goodsTypeService.list();
        model.addAttribute("goodsTypeList",goodsTypeList);

        return "goods/add";
    }

    @RequestMapping("del")
    @ResponseBody
    public Result<?> toDel(@RequestParam(value = "id", required = true)Long id){
        goodsService.removeById(id);
        return Result.success();
    }
    @Value("${upload.path}")
    private String path;

    @RequestMapping("upload")
    @ResponseBody
    public Result<?> toUpload(MultipartFile file) throws IOException {
        int start = file.getOriginalFilename().lastIndexOf(".");
        String extension = file.getOriginalFilename().substring(start + 1);
        String format = String.format("%s.%s", UUID.randomUUID().toString(), extension);//随机号
        file.transferTo(new File(String.format("%s%s",path , format)));

        return Result.success(String.format("http://192.168.51.23:82/%s",format));
    }

    @RequestMapping("save")
    @ResponseBody
    public Result<?> toSave(Goods goods){
        goodsService.saveOrUpdate(goods);
        return Result.success();
    }



}
